package com.citic.topview.system.controller;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.citic.topview.common.annotation.Log;
import com.citic.topview.common.security.Principal;
import com.citic.topview.common.system.vo.MenuVO;
import com.citic.topview.system.security.FormAuthenticationFilter;
import com.citic.topview.system.service.MenuService;
import com.citic.topview.system.util.CookieTool;
import com.citic.topview.system.util.ShiroUtils;
import com.citic.topview.system.util.ValidateCode;

@Controller
@RequestMapping("/a")
public class LoginController extends BaseController{

	//@Autowired
	//private UserRealm userRealm;
	
	@Autowired
	private MenuService menuService;
	
	@GetMapping({ "/", "" })
	public String welcome(Model model) {
		return "redirect:/a/index";
	}
	
	@Log("进入首页")
	@GetMapping({"/index"})
	public String index(Model model, HttpServletResponse response) {
		Principal principal = ShiroUtils.getPrincipal();
		
		if ("1".equals("0")) { // 如果用户已经被删除则跳到的登录页面
			ShiroUtils.logout();
			return "redirect:/a/login";
		}
		
		// 登录成功后，验证码计算器清零
		
		// 如果已经登录，则跳转到管理首页
		if(principal != null && !principal.isMobileLogin()){
			List<MenuVO> list = menuService.getTopList();
			model.addAttribute("menus", list);
			CookieTool.addCookie(response, "username", principal.getLoginName(), 60*60*24*7);
			return "index";
		}	
		
		return "redirect:/a/login";
	}
	
	@GetMapping({"/login"})
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = ShiroUtils.getPrincipal();
		
		// 如果已经登录，则跳转到管理首页
		if(principal != null && !principal.isMobileLogin()){
			return "redirect:/a/index";
		}		
		
		Cookie cookie = CookieTool.getCookieByName(request, "username");
		if(cookie != null) {
			model.addAttribute("username", cookie.getValue());
		}
		
		return "login";
	}
	
	@PostMapping({"/login"})
	String loginFail(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = ShiroUtils.getPrincipal();
		
		// 如果已经登录，则跳转到管理首页
		if(principal != null && !principal.isMobileLogin()){
			return "redirect:/a/index";
		}
		
		String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
		boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
		boolean mobileLogin = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
		String exception = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String message = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);
		
		if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")){
			message = "用户或密码错误, 请重试.";
		}
		
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MOBILE_PARAM, mobileLogin);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);
		
		// 登录失败，删除session中的验证码
		ShiroUtils.getSession().removeAttribute(ValidateCode.VALIDATE_CODE);
		
		return "redirect:/a/login";
	}
	
	@GetMapping("/validateCode")
	public void validateCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		
		String width = request.getParameter("width");
		String height = request.getParameter("height");
		if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
			ValidateCode.w = NumberUtils.toInt(width);
			ValidateCode.h = NumberUtils.toInt(height);
		}
		
		BufferedImage image = new BufferedImage(ValidateCode.w, ValidateCode.h, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();

		ValidateCode.createBackground(g);

		String s = ValidateCode.createCharacter(g);
		ShiroUtils.getSession().setAttribute(ValidateCode.VALIDATE_CODE, s);

		g.dispose();
		OutputStream out = response.getOutputStream();
		ImageIO.write(image, "JPEG", out);
		out.close();
	}
	
	@Log("登出")
	@GetMapping("/logout")
	String logout() {
		ShiroUtils.logout();
		return "redirect:/a/login";
	}
	
	@RequestMapping("/unauthorized")
    public String unauthorized(HttpSession session, Model model) {
        return "unauthorized";
    }
}
